package com.situ.blog.dao.impl;

import com.situ.blog.dao.IBlogDao;
import com.situ.blog.pojo.Blog;
import com.situ.blog.pojo.query.BlogQuery;
import com.situ.blog.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.List;

public class BlogDaoImpl implements IBlogDao {
    private JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());

    @Override
    public List<Blog> list(BlogQuery blogQuery) {
        String sql = "SELECT * FROM blog WHERE 1=1";
        //构造一个List存所有的条件
        List<Object> queryList = new ArrayList<>();
        String queryName = blogQuery.getName();
        if (queryName != null && !"".equals(queryName)) {
            sql += " AND name LIKE ?";
            queryList.add("%" + queryName + "%");
        }
        Integer typeId = blogQuery.getTypeId();
        if (typeId != null) {
            sql += " AND type_id=?";
            queryList.add(typeId);
        }
        List<Blog> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Blog.class), queryList.toArray());;
        return list;
    }
}
